<template>
  <div class="pages-content-add">
    <el-dialog
      v-model="centerDialogVisible"
      :title="title"
      width="30%"
      destroy-on-close
      center
    >
      <MyForm
        :formConfigure="formConfig"
        v-model="formData"
        :collayout="{ xl: 24 }"
      ></MyForm>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handBtnClick"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import MyForm from '@/base-ui/index'
import { useStore } from 'vuex'

export default defineComponent({
  name: 'pages-content-add',
  components: {
    MyForm
  },
  props: {
    formConfig: {
      type: Array,
      require: true
    },
    title: {
      type: String,
      default: ''
    },
    defaultConfig: {
      type: Object,
      default: () => ({})
    },
    pageName: {
      type: String,
      require: true
    },
    treeForm: {
      type: Object,
      default: () => ({})
    }
  },
  setup(prop) {
    const centerDialogVisible = ref(false)
    const formData = ref<any>({})
    watch(
      () => prop.defaultConfig,
      (newValue) => {
        prop.formConfig?.forEach((v: any) => {
          formData.value[`${v.field}`] = newValue[`${v.field}`]
        })
      }
    )
    const store = useStore()
    //点击确定发起请求
    const handBtnClick = () => {
      centerDialogVisible.value = false
      //判断是编辑确定还是添加确定
      if (Object.keys(prop.defaultConfig).length > 0) {
        //编辑确定
        store.dispatch('system/editPageData', {
          pagesName: prop.pageName,
          id: prop.defaultConfig.id,
          configInfo: {
            ...formData.value,
            ...prop.treeForm
          }
        })
      } else {
        //添加确定
        store.dispatch('system/createPageData', {
          pagesName: prop.pageName,
          configInfo: {
            ...formData.value,
            ...prop.treeForm
          }
        })
      }
    }
    return { centerDialogVisible, formData, handBtnClick }
  }
})
</script>

<style lang="less" scoped></style>
